package tts.controller.users;

import org.springframework.beans.factory.annotation.Autowired;

import tts.controller.RedirectAction;
import tts.dao.UsersHome;
import tts.model.Users;

public class ChangePwd extends RedirectAction{

	//fields
	private static final long serialVersionUID = 7831832012895249590L;
	@Autowired
	private UsersHome usersHome;
	private String username;
	private String currentPassword;
	private String newPassword;
	private String confirmPassword;

	//get & set
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getCurrentPassword() {
		return currentPassword;
	}
	public void setCurrentPassword(String currentPassword) {
		this.currentPassword = currentPassword;
	}
	public String getNewPassword() {
		return newPassword;
	}
	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}
	public String getConfirmPassword() {
		return confirmPassword;
	}
	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	//methods
	public String changePwd() {
		try {
			Users user = usersHome.findByUsername(this.username);
			if (!(user.getPassword().equals(this.currentPassword))) {
				addFieldError("currentPassword", getText("val.pwd.invalid"));
				return INPUT;
			}
			usersHome.changePwd(this.username, this.newPassword);
		} catch (RuntimeException e) {
			addActionError(e.getMessage());
			return ERROR;
		}
		addActionMessage(getText("pwd.changed"));
		return SUCCESS;
	}
}